package com.guddqs.monkey.shop.utils;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author wq
 * @date 2018/9/18
 */
@Component
public class MailService {

    @Resource(name = "mailSender")
    private JavaMailSender javaMailSender;
    @Value("${mail.from}")
    private String from;
    @Value("${mail.dev}")
    private boolean dev;

    /**
     * @param to:      对方邮箱
     * @param subject: 邮件主题
     * @param content: 邮件内容
     */
    public void sendSimpleMail(String to, String subject, String content) {
        send(to, subject, content);
    }

    /**
     * @param tos:     对方们的邮箱
     * @param subject: 邮件主题
     * @param content: 邮件内容
     */
    public void sendSimpleMail(String[] tos, String subject, String content) {
        send(tos, subject, content);
    }

    private void send(Object to, String subject, String content) {
        if (dev) {
            return;
        }
        Logger.getLogger(MailService.class).info("send mail--> subject:" + subject + " from:" + from);
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true, "UTF-8");
            if (to instanceof String[]) {
                helper.setTo((String[]) to);
            } else {
                helper.setTo(to.toString());
            }

            helper.setFrom(from);
            helper.setSubject(subject);
            helper.setText(content, true);
            javaMailSender.send(message);
            Logger.getLogger(MailService.class).info("send success!");
        } catch (MessagingException e) {
            Logger.getLogger(MailService.class).error("send mail error: " + e);
            e.printStackTrace();
        }
    }

}
